package com.cangxuan.app.ui;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import com.alibaba.fastjson.JSONObject;
import com.cangxuan.app.R;
import com.cangxuan.app.entity.Article;
import com.cangxuan.app.ui.user.ArticleContentActivity;
import com.cangxuan.app.utils.HttpUtils;
import com.google.android.material.tabs.TabLayout;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
 * 公告
 * 作者：田凯
 */
public class AnnouncementsActivity extends BaseActivity {

    /**
     * 文章类数据适配器
     */
    class ArticleAdapter extends BaseAdapter {

        private List<Article> articleList;

        public ArticleAdapter(List<Article> articleList) {
            this.articleList = articleList;
        }

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        @Override
        public int getCount() {
            return articleList.size();
        }

        @Override
        public Object getItem(int i) {
            return articleList.get(i);
        }

        @Override
        public long getItemId(int i) {
            return articleList.get(i).getId();
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            //声明视图持有类实例
            ViewHolder viewHolder;
            if (view == null) {
                //实例view对象
                view = LayoutInflater.from(getApplicationContext()).inflate(
                        R.layout.activity_article_list_item, viewGroup, false);
                //当ListView第一次获取项的视图时
                viewHolder = new ViewHolder();
                //给viewHolder中的属性（控件）进行初始化
                viewHolder.txtArticleTitle = view.findViewById(R.id.txt_article_title);
                viewHolder.txtArticleType = view.findViewById(R.id.txt_article_type);
                viewHolder.txtArticlePublishTime = view.findViewById(R.id.txt_article_publish_time);


//                viewHolder.btnArticleShow = view.findViewById(R.id.btn_article_show);
                //将viewHolder设置在view的tag属性中，用于下一次getView时，即可从view的tag属性中获取。
                view.setTag(viewHolder);
            } else {
                //当ListView后面再获取项的视图时
                viewHolder = (ViewHolder) view.getTag();
            }
            //先取出对应下标的Article
            Article article = articleList.get(i);
            //给viewHolder中的控件绑定数据
            viewHolder.txtArticleTitle.setText(article.getTitle());
            viewHolder.txtArticleType.setText(article.getTypeName());

            if(article.getPublishTime()!=null){
                viewHolder.txtArticlePublishTime.setText(article.getPublishTime().format(formatter));
            }

            return view;
        }

        /**
         * 视图持有类，
         * 该类的属性会包含ListView的项里面需要动态设置值的控件
         */
        class ViewHolder{
            TextView txtArticleTitle;
            TextView txtArticleType;
            TextView txtArticlePublishTime;

        }

    }

    //文章列表
    ListView listviewAnnouncements;

    List<Article> articleList;
    Handler handler=new Handler();
    LinearLayout contentLoading;
    TextView txtNodata;
    TabLayout tabHead;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_article);
        setTitle("新闻公告");
        //绑定控件
        listviewAnnouncements = findViewById(R.id.listview_announcements);
        tabHead=findViewById(R.id.tabHead);
        txtNodata=findViewById(R.id.txtNodata);
        contentLoading=findViewById(R.id.contentLoading);

        articleList =new ArrayList<>();
        //创建文章适配器
        ArticleAdapter articleAdapter = new ArticleAdapter(articleList);
        //给listviewArticle绑定适配器
        listviewAnnouncements.setAdapter(articleAdapter);

        listviewAnnouncements.setVisibility(View.GONE);
        txtNodata.setVisibility(View.GONE);
        contentLoading.setVisibility(View.VISIBLE);

        articleList.clear();
        Thread thread1=new Thread(() -> {
            String get = HttpUtils.get("/api/article/get/1",null) ;
            JSONObject jsonResponse = JSONObject.parseObject(get);
            List value = (List) jsonResponse.get("value");
            for(Object o:value) {
                Map o1 = (Map) o;
                articleList.add(new Article(Integer.parseInt(o1.get("id").toString()), o1.get("title").toString(), o1.get("name").toString(), LocalDateTime.parse(o1.get("publishTime").toString().replace(" ","T"))));
            }
            handler.post(()->{
                articleAdapter.notifyDataSetChanged();
                listviewAnnouncements.setVisibility(value.size()>0?View.VISIBLE:View.GONE);
                contentLoading.setVisibility(View.GONE);
                //如果获取的是0条数据，则显示 txtNoData
                txtNodata.setVisibility(value.size() == 0 ? View.VISIBLE : View.GONE);

            });
        });
        thread1.start();
        //给listviewArticle绑定项的点击事件
        listviewAnnouncements.setOnItemClickListener((adapterView, view1, i, l) -> {
            System.out.println("点击的下标:" + i + "\tID:" + l);
            Article article = articleList.get(i);
            System.out.println("点击的项的标题：" + article.getTitle());
            Intent intent =new Intent(this, ArticleContentActivity.class);
            intent.putExtra("id", (int)l);
            startActivity(intent);

        });

        tabHead.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            /**
             * 触发条件：选项卡发生切换后
             * @param tab 被选中那个tabItem
             */
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                articleList.clear();
                listviewAnnouncements.setVisibility(View.GONE);
                txtNodata.setVisibility(View.GONE);
                contentLoading.setVisibility(View.VISIBLE);
                //创建要显示的数据源
                //调用API接口获取数据，

                if (tab.getPosition()==0) {
                    Thread thread = new Thread(() -> {
                        String get = HttpUtils.get("/api/article/get/1", null);
                        JSONObject jsonResponse = JSONObject.parseObject(get);
                        List value = (List) jsonResponse.get("value");
                        for (Object o : value) {
                            Map o1 = (Map) o;
                            articleList.add(new Article(Integer.parseInt(o1.get("id").toString()), o1.get("title").toString(), o1.get("name").toString(), LocalDateTime.parse(o1.get("publishTime").toString().replace(" ", "T"))));
                        }
                        handler.post(() -> {
                            articleAdapter.notifyDataSetChanged();
                            listviewAnnouncements.setVisibility(value.size() > 0 ? View.VISIBLE : View.GONE);
                            contentLoading.setVisibility(View.GONE);
                            //如果获取的是0条数据，则显示 txtNoData
                            txtNodata.setVisibility(value.size() == 0 ? View.VISIBLE : View.GONE);

                        });
                    });
                    thread.start();
                } else if (tab.getPosition()==1) {
                    //调用API接口获取数据，
                    articleList.clear();
                    listviewAnnouncements.setVisibility(View.GONE);
                    txtNodata.setVisibility(View.GONE);
                    contentLoading.setVisibility(View.VISIBLE);
                    Thread thread=new Thread(() -> {
                        String get = HttpUtils.get("/api/article/get/2",null) ;
                        JSONObject jsonResponse = JSONObject.parseObject(get);
                        List value = (List) jsonResponse.get("value");
                        for(Object o:value) {
                            Map o1 = (Map) o;
                            articleList.add(new Article(Integer.parseInt(o1.get("id").toString()), o1.get("title").toString(), o1.get("name").toString(), LocalDateTime.parse(o1.get("publishTime").toString().replace(" ","T"))));
                        }
                        handler.post(()->{
                            articleAdapter.notifyDataSetChanged();
                            listviewAnnouncements.setVisibility(value.size()>0?View.VISIBLE:View.GONE);
                            contentLoading.setVisibility(View.GONE);
                            //如果获取的是0条数据，则显示 txtNoData
                            txtNodata.setVisibility(value.size() == 0 ? View.VISIBLE : View.GONE);

                        });
                    });
                    thread.start();

                }
            }
            /**
             * 触发条件：选项卡发生切换后
             * @param tab 离开选择的那个tabItem
             */
            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            /**
             * 触发条件：某个选项卡重复选择时
             * @param tab 重复选择的tabItem
             */
            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });

    }
}